import { Ref, UnwrapRef, onMounted, ref, toRef, toRefs, reactive } from "vue";
import { getAction } from "@/command/netTool";

export interface IDetailPageListConfig {
  refresh: (data?: any) => void;
}

export type IDetailResult<T> = [Ref<UnwrapRef<T>>, IDetailPageListConfig];

const getUrlParams = (params: any) => {
  if (typeof params == "string") {
    return {
      url: params,
      params: {},
    };
  } else {
    return params;
  }
};
export const useDetail = <T>(
  urlParams: any,
  defaultValue: T,
  { callBack } = {} as any
): IDetailResult<T> => {
  const { url, params } = getUrlParams(urlParams);
  const detail = ref(defaultValue);
  onMounted(() => {
    refresh();
  });
  const refresh = (data?: any) => {
    url &&
      getAction(url, { ...params, ...data }).then((e) => {
        if (callBack) {
          detail.value = callBack(e);
        } else {
          detail.value = e || defaultValue;
        }
      });
  };
  return [detail, { refresh }];
};

export const useDetailReactive = <T extends object>(
  url: string,
  defaultValue: T
) => {
  let detail = reactive(defaultValue);
  onMounted(() => {
    getAction(url).then((e) => (detail = Object.assign(detail, e)));
  });
  const add = (url: string) => {};
  return [detail];
};
